package com.csdj.server.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @Author zyq
 * @Date 2022/12/26 10:27
 * @ClassName: CustomUrlDecisionManager
 * @Description: TODO 判断 用户拥有的角色
 *          是否能访问当前url菜单地址
 * @Version 1.0
 * AccessDecisionManager 角色权限管理接口
 */
@Component  //实例化
public class CustomUrlDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication,
                       Object o,
                       Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        //1.循环 获取当前登录用户的角色信息
        for (ConfigAttribute configAttribute : collection) {
            //当前 url访问时需要的角色   基本资料 -->超级管理角色可以访问
            String needRole = configAttribute.getAttribute();
            //登录即可访问的角色 ROLE_LOGIN
            //判断 当前url地址所需的角色 是否 登录即可访问
            if("ROLE_LOGIN".equals(needRole)){
                //如果可以访问 判断 是否登录
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("尚未登录,请登录");
                }else {
                    return;
                }
            }

            //拿到 用户角色 权限列表集合
            Collection<? extends GrantedAuthority> authorities =
                        authentication.getAuthorities();
            //循环权限列表
            for (GrantedAuthority authority : authorities) {
                //判断 当前用户的角色 和 url地址访问所需的角色是否一致
                if(authority.getAuthority().equals(needRole)){
                    //如果一致
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足,请联系管理员");

    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
